from datetime import datetime

from playwright.sync_api import sync_playwright, Page

from common.config import Public_Data


# region token_操作
def get_token():
    """
    获取文件系统的token
    """
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()
        page.goto("http://aed.cnpdc.com")
        url = page.url
        if r"https://uap.cgnpc.com.cn/" in url:
            try:
                page.wait_for_selector('//*[@id="ifrOnceSearch"]', timeout=60000)

            except Exception as e:
                print("获取验证超时")
                return
        url = str(page.url)
        return url_to_token(url)


def get_token_from_page(page: Page):
    page.goto("http://aed.cnpdc.com")
    url = page.url
    url = page.url
    if r"https://uap.cgnpc.com.cn/" in url:
        try:
            page.wait_for_selector('//*[@id="ifrOnceSearch"]', timeout=60000)

        except Exception as e:
            print("获取验证超时")
            return
    url = str(page.url)
    return url_to_token(url)


def url_to_token(url):
    """获取网址中的token"""
    if "token" in url:
        para_list = url.split("&")[-1]
        for data_str in para_list:
            if "token" in data_str:
                return data_str


def check_token(token):
    url = "http://aed.cnpdc.com/aed/Index/AEDPortal.aspx?status=new&" + token
    with sync_playwright() as p:
        brower = p.chromium.launch(headless=True)
        page = brower.new_page()
        page.goto(url)
        try:
            page.wait_for_selector('//*[@id="ifrOnceSearch"]', timeout=20000)
            return True

        except Exception as e:
            print("获取验证超时")
            return False


def add_token_to_url(url: str):
    public_data = Public_Data()
    if public_data.Token:
        return url + f"&{public_data.Token}"
    else:
        return url


def get_token_to_public_data():
    public_data = Public_Data()
    token = get_token()
    data = public_data
    data.Token = token
    if data.Token:
        data.Token_time = datetime.now()

# endregion


# # region 文件审查 添加
# def add_attachment(driver: Page, att_file_str: str):
#     if att_file_str:
#         att_file_list = att_file_str.split(",")
#         print(att_file_list)
#         driver.get_by_text("附件信息").click()
#         for file_doc in att_file_list:
#             if file_doc:
#                 driver.locator('#sysFileUpLoad').click()
#                 # driver.wait_for_selector("#addFileXTWJ")
#                 # 添加系统文件
#                 driver.frame_locator("#frmDialogaddFileXTWJ").locator('#txtHJCode').fill(file_doc.strip())
#                 driver.frame_locator("#frmDialogaddFileXTWJ").locator('#btnSearch').click()
#                 driver.frame_locator("#frmDialogaddFileXTWJ").locator(
#                     '//div[@class="datagrid-view2"]//div[@class="datagrid-header-check"]/input').click()

